﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Restful_Api.Helpers
{
    public class PageList<T> : List<T>
    {
        public PageList(List<T> items,int count,int pageNumber,int pageSize)
        {
            TotalCount = count;
            PageSize = pageSize;
            CurrentPage = pageNumber;
            TotalPages = (int)Math.Ceiling(count / (double)pageSize);
            AddRange(items);
        }

        //当前页码
        public int CurrentPage { get; private set; }
        //总页码   
        public int TotalPages { get; private set; }
        //每页的条数
        public int PageSize { get; private set; }
        //总条数
        public int TotalCount { get; private set; }
        public bool HasPrevious => CurrentPage > 1;
        public bool HasNext => CurrentPage < TotalPages;      
        
        public static async Task<PageList<T>> CreateAsync(IQueryable<T> souce,int pageNumber,int pageSize)
        {
            var count =await souce.CountAsync();
            var items =await souce.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PageList<T>(items, count, pageNumber, pageSize);
        }
    }
}
